﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ExtendLib;
using ExtendLib.Helper;
using InterfaceLib;

namespace SmsBomb
{
    public partial class MainWindow : Form
    {
        /// <summary>
        /// 手机号
        /// </summary>
        private string _phone { get; set; }
        /// <summary>
        /// 数据库代理Ip主键 当封了Ip后 删除
        /// </summary>
        private int? _proxyId { get; set; }
        private int _logId { get; set; }
        public MainWindow()
        {
            InitializeComponent();
        }
        #region 事件
        private void 新增ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ConfigMgr cm = new ConfigMgr();
            cm.ShowDialog();
        }
        /// <summary>
        /// 开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            this.btnStart.Enabled = false;
            this.btnStop.Enabled = true;
            ControlHelper.SetStatus(EOtherType.发送状态);
            _phone = txtPhone.Text.Trim();
            //true 启用代理
            bool isProxy = ControlHelper.GetStatus(EOtherType.是否启用代理);


            if (isProxy) //刚开始就启用代理 
            {
                var proxyList = ControlHelper.GetListByType(EOtherType.代理);
                if (proxyList.Count <= 0) //没有代理Ip了 强制结束
                {
                    MessageBox.Show("配置错误，设置使用代理Ip但是没有导入代理Ip");
                    return;
                }
                ControlModel proxy = proxyList[0];
                _proxyId = proxy.Id;
                StartJob(_phone, proxy.OtherStatus.Split(':')[0], proxy.OtherStatus.Split(':')[1]);
                return;
            }
            //正常使用本机IP去访问
            StartJob(_phone, "", "");

        }
        private void timerLog_Tick(object sender, EventArgs e)
        {
            InitLog();
        }
        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            this.btnStart.Enabled = true;
            this.btnStop.Enabled = false;
            ControlHelper.SetStatus(EOtherType.发送状态, "废弃");
        }
        private void 日志管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LogMgr lm = new LogMgr();
            lm.ShowDialog();
        }

        private void 代理Ip验证ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CheckIp ci = new CheckIp();
            ci.Show();
        }

        private void 代理Ip获取配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ProxyParse pp = new ProxyParse();
            pp.Show();
        }
        private void 一键清空IpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool r = ControlHelper.BatchDelete(EOtherType.代理);
            if (r)
            {
                MessageBox.Show("清空成功，如果需要程序长时间运行 请添加代理");
            }
        }
        /// <summary>
        /// 手动同步服务器接口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 同步服务器接口ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataSync();
        }
        /// <summary>
        /// 窗口初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainWindow_Load(object sender, EventArgs e)
        {
            DataSync();
        }
        private void 官网ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //调用系统默认的浏览器   
            System.Diagnostics.Process.Start("http://bomb.hcc11.cn");
        }
        private void 不使用本机IpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool r=ControlHelper.SetStatus(EOtherType.是否启用代理);
            if (r)
            {
                MessageBox.Show("启用代理成功！");
            }
        }
        #endregion

        #region 自定义方法
        /// <summary>
        /// 初始化日志
        /// </summary>
        private void InitLog()
        {
            string where = string.Format("where Id>{0}", _logId);
            var listPages = DbHelperByDapper.GetListPages<LogModel>(1, 10, where, "Id desc");
            foreach (var model in listPages)
            {
                //表示接口都失效了
                if (model.LogMsg.IndexOf("当前接口无可用的了", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    timerLog.Enabled = false;
                }
                _logId = model.Id;
                this.logList.Items.Add("编码：" + model.Id + "时间:" + model.CreateTime + "内容：" + model.LogMsg);
            }
        }
        /// <summary>
        /// 重启任务
        /// </summary>
        private void Begin()
        {
            if (_proxyId != null) //说明取代理 再次进入时删除
            {
                ControlHelper.Delete(_proxyId.Value);
            }
            var proxyList = ControlHelper.GetListByType(EOtherType.代理);
            if (proxyList.Count <= 0) //没有代理Ip了 强制结束
            {
                LogHelper.WirteLog("代理Ip用完了，请录入后重新开始");
                SetText(btnStart, true);
                SetText(btnStop, false);

                ControlHelper.SetStatus(EOtherType.发送状态, "废弃");
                return;
            }
            var proxy = proxyList[0];
            _proxyId = proxy.Id;
            StartJob(_phone, proxy.OtherStatus.Split(':')[0], proxy.OtherStatus.Split(':')[1]);
        }
        /// <summary>
        /// 启动任务
        /// </summary>
        /// <param name="phone">手机号</param>
        /// <param name="ip">代理IP</param>
        /// <param name="port">代理端口</param>
        private void StartJob(string phone, string ip, string port)
        {
            var list = DbHelperByDapper.GetList<MsgModel>(new { Status = "正常" });
            //以下Ling 等同于foreach (MsgModel model in list)
            //{
            //    var send = new ExtendOne(model, this.txtPhone.Text.Trim());
            //    jobList.Add(send);
            //}
            List<IMsgHandler> jobList = list.Select(model =>
              new ExtendOne(model, phone, ip, port)
              ).Cast<IMsgHandler>().ToList();
            Thread th = new Thread(delegate()
            {
                ParallelLoopResult loopResult = Parallel.ForEach(jobList, (item) =>
                {
                    try
                    {
                        item.SendMsg();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WirteLog(string.Format("线程:{0}正在访问URL:{1},报错：{2}", Thread.CurrentThread.ManagedThreadId, item.InfoModel.BaseUrl, ex.Message));
                    }
                });
                if (loopResult.IsCompleted)
                {
                    if (ControlHelper.GetStatus(EOtherType.发送状态) == false)
                    {
                        LogHelper.WirteLog("当前接口无可用的了，请尝试更换IP后再开始！！！");
                    }
                    else
                    {
                        Begin();
                        LogHelper.WirteLog("当前使用的Ip已被限制，正准备读取配置！");
                    }
                }
            }) { IsBackground = true };
            th.Start();
        }

        delegate void SetTextDelagate(Button btn, bool status);

        /// <summary>
        /// 跨线程设置
        /// </summary>
        /// <param name="btn">需要操作的按钮</param>
        /// <param name="status">状态</param>
        public void SetText(Button btn, bool status)
        {
            if (btn.InvokeRequired)
            {
                SetTextDelagate d = SetText;
                this.Invoke(d, btn, status);
            }
            else
            {
                btn.Enabled = status;
            }
        }

        /// <summary>
        /// 单独开一个线程去同步服务器接口
        /// </summary>
        public void DataSync()
        {
            Thread th = new Thread(DataHelper.DataSync) { IsBackground = true };
            th.Start();
            //启用监听
            timerLog.Enabled = true;
        }
        #endregion

        private void btnTest_Click(object sender, EventArgs e)
        {
            //MsgModel m1 = new MsgModel(),
            //    m2=new MsgModel();
            //m1.BaseUrl = "www.baidu.com";
            //m2.BaseUrl = "www.baidu.com";
            //bool r = m1.Equals(m2);
            this.logList.Items.Clear();
        }







    }
}
